package com.workhours.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.workhours.dto.RestRecordRequest;
import com.workhours.entity.RestRecord;
import com.workhours.mapper.RestRecordMapper;
import com.workhours.vo.UserStatusResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * 休息记录服务类
 *
 * @author WorkHours
 * @since 2025-09-19
 */
@Service
public class RestRecordService {
    
    private static final Logger log = LoggerFactory.getLogger(RestRecordService.class);
    
    @Autowired
    private RestRecordMapper restRecordMapper;
    
    @Autowired
    private AuthService authService;
    
    /**
     * 添加休息记录
     *
     * @param request 休息记录请求
     * @return 新增的休息记录
     */
    public UserStatusResponse.RestRecordVO addRestRecord(RestRecordRequest request) {
        Long userId = authService.getCurrentUserId();
        LocalDate startDate = request.getStartDate();
        LocalDate endDate = request.getEndDate();
        String description = request.getDescription();
        
        log.info("添加休息记录，userId: {}, startDate: {}, endDate: {}", userId, startDate, endDate);
        
        // 验证业务规则
        validateRestRecord(userId, startDate, endDate, null);
        
        // 创建休息记录
        RestRecord record = new RestRecord(userId, startDate, endDate, description);
        int result = restRecordMapper.insert(record);
        
        if (result <= 0) {
            throw new RuntimeException("添加休息记录失败");
        }
        
        log.info("休息记录添加成功，recordId: {}", record.getId());
        return new UserStatusResponse.RestRecordVO(record);
    }
    
    /**
     * 更新休息记录
     *
     * @param id 记录ID
     * @param request 休息记录请求
     * @return 更新后的休息记录
     */
    public UserStatusResponse.RestRecordVO updateRestRecord(Long id, RestRecordRequest request) {
        Long userId = authService.getCurrentUserId();
        LocalDate startDate = request.getStartDate();
        LocalDate endDate = request.getEndDate();
        String description = request.getDescription();
        
        log.info("更新休息记录，recordId: {}, userId: {}, startDate: {}, endDate: {}", id, userId, startDate, endDate);
        
        // 查询记录是否存在且属于当前用户
        RestRecord existingRecord = restRecordMapper.selectById(id);
        if (existingRecord == null || !existingRecord.getUserId().equals(userId)) {
            throw new RuntimeException("休息记录不存在或无权限修改");
        }
        
        // 验证业务规则
        validateRestRecord(userId, startDate, endDate, id);
        
        // 更新记录
        existingRecord.setStartDate(startDate);
        existingRecord.setEndDate(endDate);
        existingRecord.setDescription(description != null ? description : "");
        
        int result = restRecordMapper.updateById(existingRecord);
        if (result <= 0) {
            throw new RuntimeException("更新休息记录失败");
        }
        
        log.info("休息记录更新成功，recordId: {}", id);
        return new UserStatusResponse.RestRecordVO(existingRecord);
    }
    
    /**
     * 删除休息记录
     *
     * @param id 记录ID
     */
    public void deleteRestRecord(Long id) {
        Long userId = authService.getCurrentUserId();
        
        log.info("删除休息记录，recordId: {}, userId: {}", id, userId);
        
        // 查询记录是否存在且属于当前用户
        RestRecord existingRecord = restRecordMapper.selectById(id);
        if (existingRecord == null || !existingRecord.getUserId().equals(userId)) {
            throw new RuntimeException("休息记录不存在或无权限删除");
        }
        
        int result = restRecordMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除休息记录失败");
        }
        
        log.info("休息记录删除成功，recordId: {}", id);
    }
    
    /**
     * 验证休息记录的业务规则
     *
     * @param userId 用户ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param excludeId 排除的记录ID（更新时使用）
     */
    private void validateRestRecord(Long userId, LocalDate startDate, LocalDate endDate, Long excludeId) {
        // 1. 开始日期不能晚于结束日期
        if (endDate != null && startDate.isAfter(endDate)) {
            throw new RuntimeException("开始日期不能晚于结束日期");
        }
        
        // 2. 结束日期不能是未来日期
        if (endDate != null && endDate.isAfter(LocalDate.now())) {
            throw new RuntimeException("结束日期不能是未来日期");
        }
        
        // 3. 检查与其他记录的冲突
        QueryWrapper<RestRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        
        List<RestRecord> existingRecords = restRecordMapper.selectList(queryWrapper);
        
        for (RestRecord existing : existingRecords) {
            LocalDate existingStart = existing.getStartDate();
            LocalDate existingEnd = existing.getEndDate() != null ? existing.getEndDate() : LocalDate.now();
            LocalDate currentEnd = endDate != null ? endDate : LocalDate.now();
            
            // 检查是否有重叠
            if (!(currentEnd.isBefore(existingStart) || startDate.isAfter(existingEnd))) {
                throw new RuntimeException("休息时间与现有记录冲突：" + existingStart + " 到 " + 
                    (existing.getEndDate() != null ? existing.getEndDate() : "进行中"));
            }
        }
    }
}
